#!/usr/bin/env python
# -*-coding:UTF-8-*-
# Author: chenzuoqing@126.com
# Create: 2018/8/15 15:31
# File  : inception.py

"""

"""

import pymysql
from devops.settings import INCEPTION


class Inception(object):

    def __init__(self, sql, dbname=''):
        self.sql = sql
        self.dbname = dbname

    def inception_handle(self, dbaddr):
        """
        连接inception执行SQL
        :param dbaddr:
        :return:
        """
        host = INCEPTION['inc']['host']
        port = INCEPTION['inc']['port']
        user = INCEPTION['inc']['user']
        passwd = INCEPTION['inc']['password']
        charset = INCEPTION['inc']['charset']
        use_unicode = INCEPTION['inc']['use_unicode']
        status = 0
        sql = '/* {} */\
          inception_magic_start;\
          use {}; {} inception_magic_commit;'.format(dbaddr, self.dbname, self.sql)
        try:
            # debug
            # conn = pymysql.connect(host='127.0.0.1', user='root', passwd='', port=6669, db='',
            #                        use_unicode=True, charset="utf8")  # 连接inception
            conn = pymysql.connect(host=host, user=user,
                                   passwd=passwd, port=port,
                                   db='', use_unicode=use_unicode,
                                   charset=charset)
            cur = conn.cursor()
            cur.execute(sql)
            result = cur.fetchall()
            cur.close()
            conn.close()
        except pymysql.Error as e:
            status = -1
            result = "Mysql Error {}: {}".format(e.args[0], e.args[1])
        return {'result': result, 'status': status}

    def manual(self):
        """
        连接inception备份库取备份的回滚SQL
        :return:
        """
        host = INCEPTION['backup']['host']
        port = INCEPTION['backup']['port']
        user = INCEPTION['backup']['user']
        passwd = INCEPTION['backup']['password']
        charset = INCEPTION['backup']['charset']

        try:
            # debug
            # conn = pymysql.connect(host = '127.0.0.1', port = 3306, user = 'root', passwd = '123456',
            #                        db = dbname, charset = 'utf8')  # 连接回滚库
            conn = pymysql.connect(host=host, port=port,
                                   user=user, passwd=passwd,
                                   db=self.dbname, charset=charset)
            conn.autocommit(True)
            cur = conn.cursor()
            cur.execute(self.sql)
        except Exception as e:
            print(e)
            return []
        else:
            return cur.fetchall()

    def get_back_table(self):
        return self.manual()[0][0]

    def get_back_sql(self):
        per_rollback = self.manual()
        back_sql = ''
        for i in per_rollback:
            back_sql += i[0]
        return back_sql

    def get_index_list(self):
        res = self.manual()[3:]
        return [index_info[0] for index_info in res]
